package com.hbsc.controller;

import com.hbsc.config.Constants;
import com.hbsc.domain.RegisterVo;
import com.hbsc.service.ImageService;
import com.hbsc.service.RegisterService;
import com.hbsc.service.YqTestService;
import com.hbsc.utils.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.Random;

/**
 * Created by xvdong on 2017-10-16.
 */
@Controller
public class BaseController {
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(BaseController.class);

    // 字符数量
    private static final int SIZE = 4;
    // 干扰线数量
    private static final int LINES = 5;
    // 宽度
    private static final int WIDTH = 80;
    // 高度
    private static final int HEIGHT = 50;
    // 字体大小
    private static final int FONT_SIZE = 30;

    @Autowired
    private ImageService imageService;
    @Autowired
    private YqTestService yqTestService;
    @Autowired
    private RegisterService registerService;

    @RequestMapping("/")
    public String index(){
        logger.debug("123");
        return "index";
    }

    public Map userInfo(HttpServletRequest request){
        return (Map) request.getSession().getAttribute(Constants.USER_INFO);
    }

    @RequestMapping("/imageCode")
    @ResponseBody
    public Boolean createImageCode(HttpServletRequest request, HttpServletResponse resp){
        Object[] objs = new  Object[]{"-1","-1"};
        String openid = request.getParameter("openid");
        RegisterVo registerVo = yqTestService.queryPayRecodeInfo(openid);
        if(registerVo != null){
            if(StringUtils.isEmpty(registerVo.getPayRecodeNum())){//报了名，付款数据有，但付款验证码为空
                return false;
            }
            logger.info("===========验证码从数据库获取===================");
            // 1.创建空白图片
            BufferedImage image = new BufferedImage(
                    WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            // 2.获取图片画笔
            Graphics graphic = image.getGraphics();
            // 3.设置画笔颜色
            graphic.setColor(Color.LIGHT_GRAY);
            // 4.绘制矩形背景
            graphic.fillRect(0, 0, WIDTH, HEIGHT);

            StringBuffer sb = new StringBuffer();
            char [] stringArr = registerVo.getPayRecodeNum().toCharArray();
            Random ran = new Random();
            for (int i = 0; i <SIZE; i++) {
                // 设置随机颜色
                graphic.setColor(ImageUtil.getRandomColor());
                // 设置字体大小
                graphic.setFont(new Font(
                        null, Font.BOLD + Font.ITALIC, FONT_SIZE));
                // 画字符
                graphic.drawString(
                        stringArr[i] + "", i * WIDTH / SIZE, HEIGHT-15);
                // 记录字符
                sb.append(stringArr[i]);
            }
            // 6.画干扰线
            for (int i = 0; i < LINES; i++) {
                // 设置随机颜色
                graphic.setColor(ImageUtil.getRandomColor());
                // 随机画线
                graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
                        ran.nextInt(WIDTH+12), ran.nextInt(HEIGHT+12));
            }
            objs[0]=sb.toString();
            objs[1]=image;
        }else{
            Long count = registerService.queryRegisterInfoCount(openid);
            if(count != null && count>0){//报了名，但没有存付款数据
                return false;
            }
           logger.info("===========验证码 随机生成===================");
           objs = imageService.createImage();
        }
        logger.info("验证码生成对象：{}",objs);
        // 将生产的验证码保存到Session中
        request.getSession().setAttribute("CheckImgValue", objs[0].toString());
        BufferedImage image = (BufferedImage) objs[1];
        // 设置图像缓存为no-cache。
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);

        resp.setContentType("image/jpeg");

        // 将最终生产的验证码图片输出到Servlet的输出流中
        ServletOutputStream sos = null;
        try {
            sos = resp.getOutputStream();
            ImageIO.write(image, "jpeg", sos);
            sos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }
}
